﻿<%@ WebHandler Language="C#" Class="Apollo.Website.CSVEntityList" %>

using System;
using System.Linq;
using System.Web;
using System.Collections.Generic;
using System.Reflection;
using Apollo;
using Apollo.Core;
using NHibernate;
using NHibernate.Mapping;

namespace Apollo.Website
{
    public class CSVEntityList : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        public int entityId;

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/csv";
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int entityId = 0;
            if (int.TryParse(context.Request["EntityId"], out entityId))
            {
                Entity entity = Apollo.Application.Meta<Entity>()
                            .SingleOrDefault<Entity>(e => e.Id == entityId);

                if (entity != null)
                {
                    LanguageDefinition ld = Apollo.Application.Meta<LanguageDefinition>()
                    .SingleOrDefault<LanguageDefinition>(l => l.Type == "Entity"
                        && l.CodeHi == entity.Id.ToString()
                        && l.Language.Id == Apollo.Application.CurrentLanguage.Id);

                    string csvFileName = ld != null ? ld.DisplayName : entity.Name + " list";
                    csvFileName = csvFileName.Replace(" ", "_")
                        .Replace("'", "").Replace("\"", "")
                        .Replace(";", "").Replace(":", "").Replace(",", "").Replace(".", "")
                        .Replace(">", "").Replace("<", "").Replace("=", "");

                    context.Response.AddHeader("Content-Disposition", "attachment;filename=" + csvFileName + ".csv");

                    GetReponseForEntity(context, entity);
                }
                else
                    context.Response.End();
            }
            else
                context.Response.End();
        }


        protected void GetReponseForEntity(HttpContext context, Entity entity)
        {
            string columns = context.Request["c"];

            ProjectionManager manager = new ProjectionManager(columns, entity.MappedClass);

            // add order by
            string orderBy = context.Request["sidx"];
            string orderDirection = context.Request["sord"];
            if (!string.IsNullOrEmpty(orderBy))
                manager.AddOrder(orderBy, orderDirection.ToLower() == "asc");

            // add filter
            if (!string.IsNullOrEmpty(entity.CurrentFilter))
                manager.AddFilter(entity.CurrentFilter); // from entity

            string baseFilter = context.Request["f"];
            if (!string.IsNullOrEmpty(baseFilter))
                manager.AddFilter(baseFilter); // from base
                
            string csvHeader = "";
            foreach (ProjectionManagerItem item in manager.Items)
            {
                if (csvHeader != "")
                    csvHeader += ",";

                if(item.Aggregation == ProjectionAggregate.None)
                    csvHeader += item.Projection.DisplayName;
                else
                    csvHeader += item.Aggregation.ToString() + "(" + item.Projection.DisplayName + ")";
            }

            context.Response.Write(csvHeader + Environment.NewLine);

            context.Response.Write(manager.ToCSV());
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
